﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BL;
using System.Drawing;
namespace DokterAfspraken.DoctorPages
{
    public partial class DokterWizard : System.Web.UI.Page
    {

        // <<<< //
        // WDRO //
        // <<<< //

        // general data
        private int daysPerWeek = 7;
        private string[] namesOfDays = new string[7] { "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag" };
        private enum Days { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };


        // strings to indicate working and non-working hours
        private string work = "Spreekuur";
        private string play = "Vrij";


        // doctor data: id & time per appointment

        //// RELEASE
        //private int doctorID = 0;
        //private int timeInterval = 0;

        //// DEBUG
        private int doctorID = 4;
        private int timeInterval = 240;

        // >>>> //
        // WDRO //
        // >>>> //

        /*
        protected void Page_PreInit(object sender, EventArgs e)
        {
            LoginFactory myLoginFactory = new LoginFactory();
            myLoginFactory.LoginReqAdmin();
        }
        */
        
        protected void Page_Load(object sender, EventArgs e)
        {
            DataModelManager db = new DataModelManager();
            try
            {
                int artsID = int.Parse(System.Web.HttpContext.Current.Session["dokterspraktijk_artsID"].ToString());
                Artsen mijnArts = db.getArtsInfo(artsID)[0];
                if (!Page.IsPostBack)
                {
                    txtGebruikernaam.Text = db.getArtsGebruikersnaam(artsID);
                    txtWachtwoord.Text = db.getPaswoord(txtGebruikernaam.Text);
                    if (txtGebruikernaam.Text != "")
                    {
                        txtGebruikernaam.ReadOnly = true;
                    }
                    txtVoornaam.Text = mijnArts.Voornaam;
                    txtAchternaam.Text = mijnArts.Achternaam;
                    txtStraat.Text = mijnArts.Straat;
                    txtHuisnummer.Text = mijnArts.Huisnummer;
                    txtGemeente.Text = mijnArts.Gemeente;
                    txtPostcode.Text = mijnArts.Postcode;
                    txtTelefoon.Text = mijnArts.Telefoon;
                    txtGSM.Text = mijnArts.Mobiel;
                    txtEmail.Text = mijnArts.Email;
                    txtDuurAfspraak.Text = mijnArts.DuurAfspraak.ToString();
                    TxtUniekePraktijkID.Text = db.getPraktijkIDOpArtsID(artsID).ToString();
                    txtVoorboekperiode.Text = mijnArts.VoorboekPeriode.ToString();
                    if (mijnArts.Geslacht == "M")
                    {
                        RbtnMan.Checked = true;
                    }
                    else if (mijnArts.Geslacht == "V")
                    {
                        rbtnVrouw.Checked = true;
                    }
                    if (mijnArts.LoginVereist)
                    {
                        chkbLoginVereist.Checked = true;
                    }
                }

            }
            catch
            {
            }
        }
    Artsen NieuweArts = new Artsen();
    Model.Login GebruikersnaamEnPasswoord = new Model.Login();
    Praktijken uniekepraktijkid = new Praktijken();
    ArtsenInPraktijken artsinpraktijken = new ArtsenInPraktijken();
    DataModelManager queries = new DataModelManager();

        protected void StartNextButton_Click(object sender, EventArgs e)
        {

            uniekepraktijkid.PraktijkID = int.Parse(TxtUniekePraktijkID.Text);

            NieuweArts.Voornaam = txtVoornaam.Text;
            NieuweArts.Achternaam = txtAchternaam.Text;
            NieuweArts.Straat = txtStraat.Text;
            NieuweArts.Huisnummer = txtHuisnummer.Text;
            NieuweArts.Postcode = txtPostcode.Text;
            NieuweArts.Gemeente = txtGemeente.Text;
            NieuweArts.Telefoon = txtTelefoon.Text;
            NieuweArts.Mobiel = txtGSM.Text;
            NieuweArts.Email = txtEmail.Text;
            #region NieuweArts.Geslacht if statement
            if (RbtnMan.Checked)
            {
                NieuweArts.Geslacht = "M";
            }
            else if(rbtnVrouw.Checked)
            {
                NieuweArts.Geslacht = "V";
            }
            #endregion
            NieuweArts.DuurAfspraak = int.Parse(txtDuurAfspraak.Text);
            NieuweArts.VoorboekPeriode = int.Parse(txtVoorboekperiode.Text);
            #region NieuweArts.LoginVereist if statement
            if(chkbLoginVereist.Checked)
            {
                NieuweArts.LoginVereist = true;
            }
            else if(!chkbLoginVereist.Checked)
            {
                NieuweArts.LoginVereist = false;
            }
#endregion


            if (Session["dokterspraktijk_artsID"] == null)
            {
                if (queries.checkGebruikersnaamBeschikbaar(txtGebruikernaam.Text))
                {

                    // insert de dokter en login van dokter
                    queries.insertArtsen(NieuweArts);

                    // WDRO
                    GebruikersnaamEnPasswoord.Gebruikersnaam = txtGebruikernaam.Text;
                    GebruikersnaamEnPasswoord.Paswoord = txtWachtwoord.Text;
                    GebruikersnaamEnPasswoord.Type = "Arts";
                    int tempArtsID = queries.getArtsIDOpNaam(txtVoornaam.Text, txtAchternaam.Text);
                    GebruikersnaamEnPasswoord.PersoonID = tempArtsID;
                    NieuweArts.ArtsID = tempArtsID;
                    // WDRO

                    queries.insertLogin(GebruikersnaamEnPasswoord);


                    // insert dokter in de praktijk
                    //queries.insertArstenInPraktijken(artsinpraktijken);
                }
                else 
                {
                    Response.Write("Sorry, deze gebruiksnaam is al bezet!"); 
                }
            }
            else
            {
                int denID = queries.getArtsIDOpNaam(txtVoornaam.Text,txtAchternaam.Text);
                
                #region geslachtcheck
                            if (RbtnMan.Checked)
                        {
                            NieuweArts.Geslacht = "M";
                        }
                        else if(rbtnVrouw.Checked)
                        {
                            NieuweArts.Geslacht = "V";
                        }
                #endregion
                #region loginvereistcheck
                if(chkbLoginVereist.Checked)
                {
                    NieuweArts.LoginVereist = true;
                    
                }
                else if(!chkbLoginVereist.Checked)
                {
                    NieuweArts.LoginVereist = false;
                }
            #endregion

                queries.updateArtsAlles(denID, txtVoornaam.Text, txtAchternaam.Text, txtStraat.Text, txtHuisnummer.Text, txtGemeente.Text, txtPostcode.Text, txtTelefoon.Text, txtGSM.Text, txtEmail.Text, NieuweArts.Geslacht, int.Parse(txtDuurAfspraak.Text), NieuweArts.LoginVereist, int.Parse(txtVoorboekperiode.Text));
 
            }

            // voor Wim zijn ding de artsID
            int IDvoorWim = queries.getArtsIDOpNaam(txtVoornaam.Text, txtAchternaam.Text);
            Session["artsIDvoorWim"] = IDvoorWim;

            // WDRO
            BuildScheduleTable();
            // WDRO

        }

        // <<<< //
        // WDRO //
        // <<<< //

        private void BuildScheduleTable()
        {

            // clear the placeholder
            PlaceHolder_ScheduleTable.Controls.Clear();


            // time per appointment as set by the doctor
            timeInterval = int.Parse(txtDuurAfspraak.Text);
            //timeInterval = 240;


            // general data
            int minutesPerHour = 60;
            int hoursPerDay = 24;
            int minutesPerDay = minutesPerHour * hoursPerDay;

            // calculate the number of intervals per day
            int intervalsPerDay = minutesPerDay / timeInterval;


            // retrieve the hidden value representing the individual cells' status
            char[] cellStatus = tbHiddenStatus.Text.ToCharArray();

            // the table that will represent the weekly schedule
            Table table = new Table();
            table.ID = "ScheduleTable";

            // the top row of the table containing the names of the days
            TableRow topRow = new TableRow();

            // a counter to determine each individual cell's id
            int ID = 0;

            // the top row's first cell
            TableCell blankTopCell = new TableCell();
            blankTopCell.ID = (ID++).ToString();
            blankTopCell.Width = new Unit(100);
            topRow.Cells.Add(blankTopCell);

            // the top row's remaining cells
            for (int i = 0; i < daysPerWeek; i++)
            {
                TableCell topCell = new TableCell();
                topCell.ID = (ID++).ToString();
                topCell.Text = namesOfDays[i];

                // javascript
                topCell.Attributes["onmousedown"] = "javascript: MouseDownTopCell(this, " + (i + 1) + ");";
                //topCell.Attributes["onmouseover"] = "javascript: MouseOverTopCell(this, " + (i+1) + ");";
                //topCell.Attributes["onmouseup"] = "javascript: MouseUpTopCell(this, " + (i+1) + ");";

                topRow.Cells.Add(topCell);
            }

            table.Rows.Add(topRow);


            // timespans are used to represent the start time and the duration of each interval
            TimeSpan startTime = new TimeSpan();
            TimeSpan timeIncrement = new TimeSpan(0, timeInterval, 0);


            // all subsequent rows
            for (int i = 0; i < intervalsPerDay; i++)
            {
                // row...
                TableRow genericRow = new TableRow();

                // first cell...
                TableCell firstCell = new TableCell();
                firstCell.ID = (ID++).ToString();
                firstCell.Text = startTime.ToString(@"hh\:mm");

                // javascript
                firstCell.Attributes["onmousedown"] = "javascript: MouseDownFirstCell(this, " + (i + 1) + ");";
                //firstCell.Attributes["onmouseover"] = "javascript: MouseOverFirstCell(this, " + (i+1) + ");";
                //firstCell.Attributes["onmouseup"] = "javascript: MouseUpFirstCell(this, " + (i+1) + ");";

                genericRow.Cells.Add(firstCell);

                // remaining cells...
                for (int j = 0; j < daysPerWeek; j++)
                {
                    TableCell cell = new TableCell();
                    cell.ID = (ID).ToString();

                    //if (Page.IsPostBack)
                    if (cellStatus.Length > 0)
                    {
                        if (cellStatus[ID] == '1')
                        {
                            cell.Text = work;
                            cell.BackColor = Color.FromName("LightGreen");
                        }
                        else
                        {
                            cell.Text = play;
                        }
                    }
                    else
                    {
                        cell.Text = play;
                    }

                    ID++;

                    cell.ToolTip = namesOfDays[j] + " " + startTime.ToString(@"hh\:mm");

                    // javascript
                    cell.Attributes["onmousedown"] = "javascript: MouseDown(this);";
                    cell.Attributes["onmouseover"] = "javascript: MouseOver(this);";
                    cell.Attributes["onmouseup"] = "javascript: MouseUp(this);";

                    genericRow.Cells.Add(cell);
                }

                table.Rows.Add(genericRow);

                startTime += timeIncrement;
            }


            // add the table to the placeholder
            PlaceHolder_ScheduleTable.Controls.Add(table);


            // initialize the hidden value representing the individual cells' status
            //if (!Page.IsPostBack)
            if (cellStatus.Length == 0)
            {
                foreach (TableRow row in table.Rows)
                {
                    foreach (TableCell cell in row.Cells)
                    {
                        tbHiddenStatus.Text += "0";
                    }
                }
            }


            // hide supporting controls, unwanted result: controls are no longer available on the page...
            //tbHiddenStatus.Visible = false;
            //tbDebug.Visible = false;


            // call javascript function
            Page.ClientScript.RegisterStartupScript(this.GetType(), "InitiateTableData", "InitiateTableData();", true);

        }

        // >>>> //
        // WDRO //
        // >>>> //

        protected void wizardDokter_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {

            // WDRO
            // verplaatst van next naar finish en functioneel aangepast
            artsinpraktijken.ArtsID = int.Parse(Session["artsIDvoorWim"].ToString()); ;
            artsinpraktijken.PraktijkID = int.Parse(TxtUniekePraktijkID.Text);
            queries.insertArstenInPraktijken(artsinpraktijken);
            // WDRO

            int IDvanpraktijkinKwestie = int.Parse(TxtUniekePraktijkID.Text);
            int IDvandokterinKwestie = queries.getArtsIDOpNaam(txtVoornaam.Text, txtAchternaam.Text);

            if (Session["dokterspraktijk_artsID"] == null)
            {

                string to = queries.getPraktijkEmail(int.Parse(TxtUniekePraktijkID.Text));
                string from = "info@telenet.be";
                string subject = "Link naar specifieke dokter";
                string body = "Hier volgt u link, voor op de praktijkwebsite. \n Agenda voor Dr. " + txtAchternaam.Text + ": PatientAgenda.aspx?ID=" + IDvandokterinKwestie + "&PraktijkID="+IDvanpraktijkinKwestie;

                // WDRO
                // nog uit te pluizen
                Mailhelper.SendMailMessage(to, from, subject, body);
                // WDRO

            }

            // <<<< //
            // WDRO //
            // <<<< //

            // start and end date
            DateTime startDate = new DateTime();
            DateTime endDate = new DateTime();


            // clear the error message
            lblError.Text = "";


            // parse the start date
            try
            {
                startDate = DateTime.Parse(tbStartDate.Text);
            }
            catch
            {
                lblError.Text = "Ongeldige startdatum!";
                BuildScheduleTable();
                return;
            }

            // parse the end date
            try
            {
                endDate = DateTime.Parse(tbEndDate.Text);
            }
            catch
            {
                lblError.Text = "Ongeldige einddatum!";
                BuildScheduleTable();
                return;
            }

            // compare start and end date
            if (startDate > endDate)
            {
                lblError.Text = "De startdatum mag niet later plaatsvinden dan de einddatum!";
                BuildScheduleTable();
                return;
            }


            // build templates for every weekday
            List<BeschikbaarheidArtsen> monday = GetDailySchedule(Days.Monday);
            List<BeschikbaarheidArtsen> tuesday = GetDailySchedule(Days.Tuesday);
            List<BeschikbaarheidArtsen> wednesday = GetDailySchedule(Days.Wednesday);
            List<BeschikbaarheidArtsen> thursday = GetDailySchedule(Days.Thursday);
            List<BeschikbaarheidArtsen> friday = GetDailySchedule(Days.Friday);
            List<BeschikbaarheidArtsen> saturday = GetDailySchedule(Days.Saturday);
            List<BeschikbaarheidArtsen> sunday = GetDailySchedule(Days.Sunday);


            // temporary date
            DateTime currentDate = startDate;

            // process every day in the given period
            while (currentDate <= endDate)
            {
                DayOfWeek dayOfWeek = currentDate.DayOfWeek;

                switch (dayOfWeek)
                {
                    case DayOfWeek.Monday:
                        InsertDailySchedule(currentDate, monday);
                        break;
                    case DayOfWeek.Tuesday:
                        InsertDailySchedule(currentDate, tuesday);
                        break;
                    case DayOfWeek.Wednesday:
                        InsertDailySchedule(currentDate, wednesday);
                        break;
                    case DayOfWeek.Thursday:
                        InsertDailySchedule(currentDate, thursday);
                        break;
                    case DayOfWeek.Friday:
                        InsertDailySchedule(currentDate, friday);
                        break;
                    case DayOfWeek.Saturday:
                        InsertDailySchedule(currentDate, saturday);
                        break;
                    case DayOfWeek.Sunday:
                        InsertDailySchedule(currentDate, sunday);
                        break;
                    default:
                        lblError.Text = "Ongeldige weekdag. Gelieve contact op te nemen met de helpdesk.";
                        return;
                }

                currentDate = currentDate.AddDays(1);
            }

            Response.Write("Uw gegevens zijn succevol bewaard.");
            Response.Redirect("Dokterkeuzescherm.aspx");

        }


        // retrieve a list with a template for the schedule of a given weekday
        private List<BeschikbaarheidArtsen> GetDailySchedule(Days day)
        {

            // the list to return
            List<BeschikbaarheidArtsen> list = new List<BeschikbaarheidArtsen>();


            // wizard control necessitates a rebuild of the schedule table...
            BuildScheduleTable();


            // the schedule table
            Table table = (Table)PlaceHolder_ScheduleTable.FindControl("ScheduleTable");


            // time per appointment as set by the doctor
            timeInterval = int.Parse(txtDuurAfspraak.Text);
            //timeInterval = 240;


            // duration of an appointment
            TimeSpan timeIncrement = new TimeSpan(0, timeInterval, 0);


            // process all cells in a specific column, depending on the weekday, to build the list
            foreach (TableRow row in table.Rows)
            {
                if (row.Cells[(int)day].Text == work)
                {

                    // determine the start time
                    string hour = row.Cells[0].Text;
                    TimeSpan startHour = TimeSpan.Parse(hour);

                    // determine the end time (a timespan larger than one day is truncated)
                    TimeSpan tempSpan = startHour + timeIncrement;
                    TimeSpan endHour = new TimeSpan(tempSpan.Hours, tempSpan.Minutes, tempSpan.Seconds);

                    // create and add item to the list
                    BeschikbaarheidArtsen ba = new BeschikbaarheidArtsen();
                    ba.StartUur = startHour;
                    ba.EindUur = endHour;

                    list.Add(ba);
                }
            }

            return list;

        }


        // insert an actual daily schedule in the database
        private void InsertDailySchedule(DateTime dateTime, List<BeschikbaarheidArtsen> list)
        {

            // the doctor's id
            doctorID = int.Parse(Session["artsIDvoorWim"].ToString());
            //doctorID = 4;


            // wrapper to access the database
            DataModelManager dmm = new DataModelManager();


            // process the list
            foreach (BeschikbaarheidArtsen item in list)
            {
                BeschikbaarheidArtsen ba = new BeschikbaarheidArtsen();
                ba.ArtsID = doctorID;
                ba.Datum = dateTime;
                ba.StartUur = item.StartUur;
                ba.EindUur = item.EindUur;
                dmm.InsertBeschikbaarheidArtsen(ba);
            }


        }

        // >>>> //
        // WDRO //
        // >>>> //
        
    }
}